'use strict';

const db = uniCloud.database();

exports.main = async (event, context) => {
  const { data = {} } = event;
  const { order_id } = data;

  if (!order_id) {
    return {
      code: 400,
      message: '订单ID不能为空',
      data: null
    };
  }

  try {
    // 直接按ID查询
    const docRes = await db.collection('food-order').doc(order_id).get();
    
    // docRes.data 可能是对象或数组，统一处理
    let orderData = docRes.data;
    if (Array.isArray(orderData)) {
      orderData = orderData[0];
    }
    
    if (!orderData) {
      return {
        code: 404,
        message: '订单不存在',
        data: null
      };
    }
    
    return {
      code: 200,
      message: '成功',
      data: orderData
    };
  } catch (err) {
    return {
      code: 500,
      message: err.message,
      data: null
    };
  }
};
